// 表单校验 - jquery-validation
// 添加自定义用户名校验规则
jQuery.validator.addMethod('checkUser', function(v){
    return /^[a-z0-9]\w{4,11}$/.test(v)
}, '用户名是由小写字母和数字开头，由数字字母下划线组成，5~12位')

// 添加自定义密码校验规则
jQuery.validator.addMethod('checkPass', function(v){
    return /\w{6,12}/.test(v)
}, '密码由数字字母下划线组成，6~12位')
// 开始校验
$('.regForm').validate({
    rules: {
        username: {
            required: true,
            minlength: 5,
            maxlength: 12,
            checkUser: true
        },
        password: {
            required: true,
            minlength: 6,
            maxlength: 12,
            checkPass: true
        },
        rpassword: {
            required: true,
            equalTo: '#password'
        },
        nickname: {
            required: true
        },
    },
   
    messages: {
        username: {
            required: '用户名不能为空',
            minlength: '用户名最短5位',
            maxlength: '用户名最长12位',
        },
        password: {
            required: '密码不能为空',
            minlength: '密码最短6位',
            maxlength: '密码最长12位',
        },
        rpassword: {
            required: '确认密码不能为空',
            equalTo: '两次密码输入不一致'
        },
        nickname: {
            required: '昵称不能为空',
        },
    },
    submitHandler(form){
        // console.log(111);
        // 将按钮禁用 - 添加加载层
        $('.but').prop('disabled', true)
        var loadId = layer.load(1, {
            shade: [1, '#000']
        })
        $.post({
            url: 'http://localhost:8888/users/register',
            data: $(form).serialize(),
        }).then(res => {
            layer.close(loadId)
            if(res.code === 1){
                layer.msg(res.message, {
                    icon: 1,
                    time: 1500
                }, function(){
                    location.href = 'login.html'
                })
            }else{
                layer.msg(res.message, {
                    icon: 2,
                    time: 1500
                }, function(){
                    $('.but').prop('disabled', false)
                })
            }
            // console.log(res);
        })
    }
})
